import { Component, OnInit } from '@angular/core';
import { SelectItem, DialogService } from 'primeng/primeng';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { HotlineUploadComponent } from '../upload/hotline-upload.component';
import { HotlineCleanComponent } from '../clean/hotline-clean.component';
import { HotlineService } from '../hotline.service';
import { MdlSnackbarService } from '@angular-mdl/core';
import { DateUtils } from '../../common/utils/DateUtils';
import { switchMap } from 'rxjs/operators';
import * as cfg from '../../common/configuration';

@Component({
    templateUrl: './hotline-stat.component.html',
    styleUrls: ['./hotline-stat.component.scss'],
    providers: [DialogService, HotlineService, MdlSnackbarService]
})
export class HotlineStatComponent implements OnInit {
    zh = cfg.DATE_ZH_CN;
    //当前选中面板
    activeIndex = 0;
    //考核序列
    kqSeq: SelectItem[] = [{ label: '街道考核', value: 0 }, { label: '部门考核', value: 1 }];
    //回访类型
    responseType: SelectItem[] = [{ label: '全部', value: 0 }, { label: '市级回访', value: 1 }, { label: '区级回访', value: 2 }];
    //诉求三率
    cols: any[] = [
        { field: 'pm', header: '排名', style: { 'width': '50px', 'text-align': 'center' } },
        { field: 'dw', header: '单位', style: { 'width': '160px', 'text-align': 'center' } },
        { field: 'yxf', header: '有效访', style: { 'text-align': 'center' } },
        { field: 'xyl', header: '响应率（%）', style: { 'text-align': 'center' } },
        { field: 'jjs', header: '解决数', style: { 'text-align': 'center' } },
        { field: 'jjl', header: '解决率（%）', style: { 'text-align': 'center' } },
        { field: 'mys', header: '满意数', style: { 'text-align': 'center' } },
        { field: 'myl', header: '满意率（%）', style: { 'text-align': 'center' } },
        { field: 'zhpf', header: '综合评分', style: { 'text-align': 'center' } },
        { field: 'slhj', header: '双率合计（%）', style: { 'text-align': 'center' } },
        { field: 'yjscz', header: '预计双差值（%）', style: { 'text-align': 'center' } },
        { field: 'qs', header: '趋势', style: { 'text-align': 'center' } }
    ];
    items: any[] = [];
    //街道承办
    streetCols: any[] = [
        { field: 'pm', header: '排名', style: { 'width': '80px', 'text-align': 'center' } },
        { field: 'jdmc', header: '街道名称', style: { 'text-align': 'center' } },
        { field: 'jrzs', header: '今日总数量', style: { 'width': '100px', 'text-align': 'center' } },
        { field: 'jrszps', header: '今日市级直派数', style: { 'width': '100px', 'text-align': 'center' } },
        { field: 'jrqzps', header: '今日区平台转派数', style: { 'width': '200px', 'text-align': 'center' } },
        { field: 'ljsl', header: '累计数量', style: { 'width': '200px', 'text-align': 'center' } },
    ];
    streetItems: any[] = [];
    //部门承办
    unitCols: any[] = [
        { field: 'pm', header: '排名', style: { 'width': '80px', 'text-align': 'center' } },
        { field: 'mc', header: '处置部门', style: { 'text-align': 'center' } },
        { field: 'ljsl', header: '今日受理数量', style: { 'width': '250px', 'text-align': 'center' } },
        { field: 'ljsl', header: '累计数量', style: { 'width': '250px', 'text-align': 'center' } },
    ];
    unitItems: any[] = [];

    start: any;
    end: any;
    selectItem: any = 0;
    respSelectItem: any = 0;

    constructor(
        private router: Router,
        private route: ActivatedRoute,
        public hotlineService: HotlineService,
        public dialogService: DialogService,
        private mdlSnackbarService: MdlSnackbarService
    ) { }

    ngOnInit() {
        //初始化查询条件
        let startDay = new Date();
        if (startDay.getDate() <= 20) {
            startDay.setMonth(startDay.getMonth() - 1);
        }
        startDay.setDate(20);
        startDay.setHours(12);
        startDay.setMinutes(0);
        startDay.setSeconds(0);
        // this.start = startDay;
        let today = new Date();
        today.setHours(12);
        today.setMinutes(0);
        today.setSeconds(0);
        // this.end = today;
        //this.calculate();

        this.route.paramMap.pipe(
            switchMap((params: ParamMap) => {
                //开始时间
                let s = params.get('start');
                if (s) {
                    this.start = DateUtils.stringToDate(s);
                } else {
                    this.start = startDay;
                }
                //结束时间
                let e = params.get('end');
                if (e) {
                    this.end = DateUtils.stringToDate(e);
                } else {
                    this.end = today;
                }
                //当前选中Tab
                let idxType = +params.get("type");
                if (idxType) {
                    this.activeIndex = idxType - 1;
                }
                //街道 or 部门 考核
                let kh = params.get("khType");
                if (kh) {
                    this.selectItem = +kh;
                }
                //回访类型
                let resp = params.get("responseType");
                if (resp) {
                    this.respSelectItem = +resp;
                }
                return this.hotlineService.calculate({
                    'start': DateUtils.dateToFormat(this.start, 'yyyy-MM-dd HH:mm:ss'), //开始时间
                    'end': DateUtils.dateToFormat(this.end, 'yyyy-MM-dd HH:mm:ss'), //截止时间
                    'khType': this.selectItem,
                    'type': this.activeIndex + 1, // 0 : 诉求三率 /1 : 街道承办统计 / 2 : 部门承办统计
                    'responseType': this.respSelectItem //响应类型
                });
            })
        ).subscribe(items => {
            if (this.activeIndex == 0) {
                //诉求三率
                this.items = items;
            } else if (this.activeIndex == 1) {
                //街道承办
                this.streetItems = items;
            } else if (this.activeIndex == 2) {
                //部门承办
                this.unitItems = items;
            }
            this.reloadStatChart(items);
        });
    }
    /** 数据上传 */
    upload($event) {
        const dialog = this.dialogService.open(HotlineUploadComponent, {
            header: ['诉求三率导入', '街道承办导入', '部门承办导入'][this.activeIndex],
            width: '80%',
            data: {
                'index': this.activeIndex
            },
            contentStyle: { 'height': $("body").height() - 80 + 'px', 'background-color': '#101E5A', 'border': '1px solid #1A2869' },
            styleClass: "stat-container-dialog"
        });
        dialog.onClose.subscribe(data => data && this.calculate());
    }
    /** 数据清理 */
    clean($event){
        const dialog = this.dialogService.open(HotlineCleanComponent, {
            header: '数据清理',
            width: '80%',
            data: {
                'index': this.activeIndex
            },
            contentStyle: { 'height': $("body").height() - 80 + 'px', 'background-color': '#101E5A', 'border': '1px solid #1A2869' },
            styleClass: "stat-container-dialog"
        });
        dialog.onClose.subscribe(data => data && this.calculate());
    }

    /** 三率/街道 Tab切换 */
    tabChanged($event) {
        this.activeIndex = $event.index;
        this.calculate();
    }

    /**计算 */
    calculate() {
        this.hotlineService.calculate({
            'start': DateUtils.dateToFormat(this.start, 'yyyy-MM-dd HH:mm:ss'), //开始时间
            'end': DateUtils.dateToFormat(this.end, 'yyyy-MM-dd HH:mm:ss'), //截止时间
            'khType': this.selectItem,
            'type': this.activeIndex + 1, // 0 : 诉求三率 /1 : 街道承办统计 / 2 : 部门承办统计
            'responseType': this.respSelectItem //响应类型
        }).subscribe(items => {
            if (this.activeIndex == 0) {
                //诉求三率
                this.items = items;
            } else if (this.activeIndex == 1) {
                //街道承办
                this.streetItems = items;
            } else if (this.activeIndex == 2) {
                //部门承办
                this.unitItems = items;
            }
            this.reloadStatChart(items);
        });
    }

    /**反查 */
    showDetail(rowData) {
        this.router.navigate(['/hotline/detail', {
            'start': DateUtils.dateToFormat(this.start, 'yyyy-MM-dd HH:mm:ss'),
            'end': DateUtils.dateToFormat(this.end, 'yyyy-MM-dd HH:mm:ss'),
            'name': rowData['dw'] || rowData['jdmc'] || rowData['mc'],
            'type': this.activeIndex + 1,
            'khType': this.selectItem, //街道、部门
            'responseType': this.respSelectItem //全部、市级回访、区级回访 
        }]);
    }

    /**导出 */
    export() {
        this.hotlineService.export({ 
            'start': DateUtils.dateToFormat(this.start, 'yyyy-MM-dd HH:mm:ss'), 
            'end': DateUtils.dateToFormat(this.end, 'yyyy-MM-dd HH:mm:ss') 
        }).subscribe();
    }

    /**加载图表 */
    reloadStatChart(items) {
        var dom = document.getElementById("chart-container");
        var myChart = echarts.init(dom);
        let option = null;
        myChart.showLoading();
        if (0 == this.selectItem && this.activeIndex != 2) {
            let mapItems = [];
            items.forEach(ele => {
                var steetName = (ele.dw || ele.jdmc || '').replace('街道', '');
                var count = ele.yxf || ele.jrzs || 0
                mapItems.push({ name: steetName, value: count });
            });
            this.hotlineService.loadMap().subscribe(geoJson => {
                myChart.hideLoading();
                echarts.registerMap('DC', geoJson);
                myChart.setOption(option = {
                    tooltip: {
                        trigger: 'item',
                        formatter: '{b}<br/>有效访：{c}'
                    },
                    series: [
                        {
                            name: '东城街道数据统计',
                            type: 'map',
                            mapType: 'DC', // 自定义扩展图表类型
                            itemStyle: {
                                normal: { label: { show: true } },
                                emphasis: { label: { show: true } }
                            },
                            data: mapItems,
                            // 自定义名称映射
                            nameMap: {
                                '北新桥': '北新桥',
                                '安定门': '安定门',
                                '东直门': '东直门',
                                '朝阳门': '朝阳门',
                                '崇外': '崇外',
                                '东华门': '东华门',
                                '东花市': '东花市',
                                '东四': '东四',
                                '景山': '景山',
                                '和平里': '和平里',
                                '建国门': '建国门',
                                '交道口': '交道口',
                                '龙潭': '龙潭',
                                '前门': '前门',
                                '体育馆': '体育馆',
                                '天坛': '天坛',
                                '永定门外': '永定门外'
                            }
                        }
                    ]
                }, true);
            });
        } else {
            let yAxis = [], seriesData = [];
            if (this.activeIndex == 2) {
                //部门承办
                let jrs = [], zs = [];
                items.forEach(element => {
                    yAxis.push(element.mc || '汇总');
                    jrs.push(element.jrzs);
                    zs.push(element.ljsl);
                });
                seriesData.push({ name: '今日数', type: 'bar', data: jrs });
                seriesData.push({ name: '累计数', type: 'bar', data: zs });
            } else {
                // 诉求三率 -- 部门
                let yxf = [], jjs = [], mys = [];
                items.forEach(element => {
                    yAxis.push(element.dw);
                    yxf.push(element.yxf);
                    jjs.push(element.jjs);
                    mys.push(element.mys);
                });
                seriesData.push({ name: '有效访', type: 'bar', data: yxf });
                seriesData.push({ name: '解决数', type: 'bar', data: jjs });
                seriesData.push({ name: '满意数', type: 'bar', data: mys });
            }

            myChart.hideLoading();
            option = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                legend: {
                    data: (this.activeIndex == 2 ? ['今日数', '累计数'] : ['有效访', '解决数', '满意数']),
                    textStyle: { 'color': 'whitesmoke' }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'value',
                    boundaryGap: [0, 0.01],
                    axisLabel: {
                        textStyle: { 'color': 'whitesmoke' }
                    }
                },
                yAxis: {
                    type: 'category',
                    axisLabel: {
                        textStyle: { 'color': 'whitesmoke' }
                    },
                    data: yAxis
                },
                series: seriesData
            };
            myChart.setOption(option, true);
        }
    }

}